<template>
  <div class="parking-statistics">
    <el-card>
      <el-form 
        :inline="true" 
        :model="formInline" 
        :rules="FormInlineRules" 
        ref="FormInlineRef" 
        class="demo-form-inline"
        @submit.prevent="fetchData"
      >
      <el-form-item label="停车场编号" prop="lotCode">
        <el-input v-model="formInline.lotCode"></el-input>
      </el-form-item>
      <el-form-item label="起始时间" prop="startTime">
        <el-config-provider :locale="locale">
          <el-date-picker
            v-model="formInline.startTime"
            type="datetime"  
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"  
            value-format="YYYY-MM-DD HH:mm:ss"  
            :locale="locale"
          />
        </el-config-provider>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-config-provider :locale="locale">
          <el-date-picker
            v-model="formInline.endTime"
            type="datetime"  
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" 
            :locale="locale"
          />
        </el-config-provider>
      </el-form-item>
        <el-form-item label="时间单位">
          <el-select v-model="formInline.timeUnit" placeholder="请选择时间单位" style="margin-left: 20px; width: 150px;">
            <el-option label="年" value="year"></el-option>
            <el-option label="月" value="month"></el-option>
            <el-option label="日" value="day"></el-option>
            <el-option label="时" value="hour"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleGenerate">生成</el-button>
          <el-button type="info" @click="resetQueryData">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 折线图卡片 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div>
              <h3>时间段内出入场数量变化</h3>
            </div>
          </template>
          <v-chart class="chart" :option="lineChartOption" />
        </el-card>
      </el-col>

      <!-- 条形图卡片 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div>
              <h3>规定单位时间段内车位占用率变化情况</h3>
            </div>
          </template>
          <v-chart class="chart" :option="barChartOption" />
        </el-card>
      </el-col>
    </el-row>
    <el-col :span="24">
      <el-card class="box-card" style="margin-top: 20px;" v-loading="isLoading" element-loading-text="加载中...">
        <template #header>
          <div class="card-header">
            <h3>财务概览</h3>
          </div>
        </template>
        <el-table :data="IncomeData" border style="width: 100%">
          <el-table-column prop="totalIncome" label="总收入(元/时)" width="600"></el-table-column>
          <el-table-column prop="feeScheduleCode" label="收费策略编号" width="600"></el-table-column>
          <el-table-column prop="hourlyRate" label="每小时费率(元/时)"></el-table-column>
          <!-- <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button size="primary" @click="handleEdit(scope.row)">动态定价</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </el-card>
    </el-col>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElDatePicker, ElSelect, ElOption, ElButton, ElMessage } from 'element-plus';
import VChart from 'vue-echarts';
import 'echarts';
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import axios from 'axios';

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
});

const IncomeData = ref([]);

const formInline = ref({
  lotCode: '',
  timeUnit: 'day',
  startTime: null,
  endTime: null
});

const FormInlineRules = {
  lotCode: [{ required: true, message: '停车场编号不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '起始时间不能为空', trigger: 'change' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }]
};

const isLoading = ref(false);
const locale = zhCn;
const FormInlineRef = ref(null);
const lineChartOption = ref({});
const barChartOption = ref({});

const fetchDataFromApi = async (params) => {
  isLoading.value = true;
  try {
    const response = await api.get('/api/v1/data-analysis/data-analysis-info', { params });
    if (response.data.code === "200") {
      return response.data.data != null ? response : null;
    } else {
      ElMessage({
        title: '错误',
        message: response.data.message,
        type: 'error',
        showClose: false
      });
      return null;
    }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取统计信息失败！' + error.message,
      type: 'error',
      showClose: false
    });
  }
};

async function handleGenerate() {
  FormInlineRef.value.validate((valid) => {
    if (valid) {
      fetchData();
    } else {
      console.log('表单验证失败!');
      return false;
    }
  });
}

async function fetchData() {
  if (!formInline.value.startTime || !formInline.value.endTime) return;
  try {
    const response = await fetchDataFromApi(formInline.value);
    if (response == null) {
      return;
    }
    // 更新折线图数据
    lineChartOption.value = {
      title: {
        text: '出入场数量'
      },
      tooltip: {},
      xAxis: {
        data: response.data.data.lineXAxisData
      },
      yAxis: {},
      series: [
        {
          name: '入场数量',
          type: 'line',
          data: response.data.data.inCounts
        },
        {
          name: '出场数量',
          type: 'line',
          data: response.data.data.outCounts
        }
      ]
    };

    // 更新条形图数据
    barChartOption.value = {
      title: {
        text: '车位占用率'
      },
      tooltip: {},
      xAxis: {
        type: 'category',
        data: response.data.data.barXAxisData
      },
      yAxis: {},
      series: [
        {
          name: '车位占用率',
          type: 'bar',
          data: response.data.data.occupancyRates
        }
        // {
        //   name: '收入占比',
        //   type: 'bar',
        //   data: response.data.data.incomeRatio // 假设这是从后端获取的收入占比数据
        // }
      ]
    };
    fetchFinancialInfo();
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '绘制图形失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
  }
}
const fetchFinancialInfo = async () => {
  if (!formInline.value.lotCode) return;
  isLoading.value = true;
  try {
      const responseLot = await api.get('/api/v1/parking-lot/parking-lot-info', {
          params: { lotCode: formInline.value.lotCode }
      });
      if (responseLot.data.code === "200" && responseLot.data.data.records != null) {
        const responseFee = await api.get('/api/v1/fee-schedule/fee-schedule-info', {
            params: { feeScheduleCode: responseLot.data.data.records[0].feeScheduleCode }
        });
        if(responseFee.data.code === "200" && responseFee.data.data.records != null){
          const responseRecord = await api.get('/api/v1/data-analysis/data-analysis-income', {
            params: formInline.value
          });
          if(responseRecord.data.code === "200" && responseRecord.data.data != null){
            IncomeData.value = [{
                feeScheduleCode: responseLot.data.data.records[0].feeScheduleCode || '',
                hourlyRate: responseFee.data.data.records[0].hourlyRate || null,
                totalIncome: responseRecord.data.data.totalIncome || 0
            }];
          } else {
              ElMessage({
                title: '错误',
                message: '计算总收入失败！' + responseRecord.data.message,
                type: 'error',
                showClose: false
            });
          }
        } else {
          ElMessage({
            title: '错误',
            message: '获取收费策略信息失败！' + responseFee.data.message,
            type: 'error',
            showClose: false
        });
      }
    } else {
        ElMessage({
          title: '错误',
          message: '获取停车场记录失败！' + responseLot.data.message,
          type: 'error',
          showClose: false
      });
    }
        // console.log(JSON.stringify(responseLot));
        // console.log(JSON.stringify(responseFee));
  } catch (error) {
      console.error('获取财务信息失败', error);
  } finally {
      isLoading.value = false;
  }
}
const resetQueryData = () => {
  formInline.value = {
    lotCode: '',
    timeUnit: 'day',
    startTime: null,
    endTime: null
  }
  // formInline.value.timeUnit = 'day'; // 直接重置 timeUnit 变量
  FormInlineRef.value.resetFields(); // 重置表单验证状态
}
</script>

<style scoped>
.parking-statistics {
  height: 100vh;
}
.chart {
  height: 400px;
}
.el-card {
  margin-bottom: 20px; /* 卡片底部外边距 */
}
</style>